<template>
  <div class="user" v-for="(user, index) of props.rank" :key="index" @click="toUser(user.id)">
    <div class="no">{{ index + 1 }}</div>
    <div>
      <el-avatar :size="40" :src="user.avatar" @error="true">
        <span>{{ user.nickname }}</span>
      </el-avatar>
    </div>
    <div style="margin-left: 10px; display: flex; justify-content: space-between; width: 100%">
      <div>
        <div>{{ user.nickname }}</div>
        <div style="display: flex; font-size: 12px; color: #6b6b6b">
          <div style="display: flex">
            粉丝数
            <div class="item">{{ titleUtil.numberTo(user.followCount) }}</div>
          </div>
          <div style="display: flex">
            获赞
            <div class="item">
              {{ user.likeCount === null ? 0 : titleUtil.numberTo(user.likeCount) }}
            </div>
          </div>
        </div>
      </div>
      <div style="width: 100px; text-align: center">
        <div style="font-size: 11px; color: #6b6b6b">
          {{ titleUtil.numberTo(user.score) }}综合指标
        </div>
        <div>
          <div v-if="userId === user.id">我</div>
          <div v-else>
            <el-button size="small" style="width: 80px" round @click.stop="followUser(user.id)"
              >关注</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import request from '@/util/request'
import titleUtil from '@/util/titleUtil'
import { useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
import { ref } from 'vue'

const router = useRouter()
const userId = JSON.parse(localStorage.getItem('user')).id

const props = defineProps({
  rank: {
    type: Array,
    required: true,
    default: () => [] // 提供一个安全的默认值
  }
})

const toUser = (userId) => {
  router.push({ name: 'UserPage', params: { userId: userId } })
}

const followUser = (id) => {
  request
    .get(`/user/follow?userId=${id}`)
    .then((res) => {
      setTimeout(() => {
        if (res.data) {
          ElNotification.success('关注成功')
        } else {
          ElNotification.success('成功取关')
        }
      })
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}
</script>

<style scoped>
.list {
  border: 1px #eee solid;
}

.user {
  padding: 15px;
  display: flex;
  height: 40px;
  border: #eee 1px solid;
}

.user:hover {
  background: #eee;
  cursor: pointer;
}

.no {
  line-height: 40px;
  margin-right: 10px;
  font-size: 18px;
}

.item {
  margin-right: 15px;
  margin-left: 5px;
}
</style>
